<script setup lang="ts">
import { computed, ref } from 'vue';

interface Comment {
  id: number
  user: string
  avatar: string
  time: string
  content: string
  likes: number
  isLiked: boolean
  replies: Reply[]
  createdAt: number
}

interface Reply {
  id: number
  user: string
  avatar: string
  time: string
  content: string
  replyTo?: string
}

// 当前文章数据
const article = ref({
  id: 1,
  title: 'Vue3 Composition API最佳实践',
  author: '前端小王子',
  avatar: '/static/images/avatar/1.jpg',
  date: '2024-08-15',
  views: 1250,
  likes: 98,
  comments: 24,
  isLiked: false,
  isFavorited: false,
  tags: ['Vue.js', '前端开发', 'Composition API'],
  content: `
    <h2>Vue3 Composition API简介</h2>
    <p>Composition API是Vue3引入的全新组件编写方式，它解决了Options API在复杂组件中代码组织混乱的问题。通过将相关逻辑组织在一起，大大提高了代码的可读性和可维护性。</p>
    
    <h2>核心特性</h2>
    <p>1. <strong>setup函数</strong>：组件的入口点，在beforeCreate之前执行</p>
    <p>2. <strong>响应式API</strong>：ref和reactive</p>
    <p>3. <strong>生命周期钩子</strong>：onMounted等</p>
    
    <h2>最佳实践</h2>
    <p>1. 按功能组织代码，而不是按选项类型</p>
    <p>2. 合理使用ref和reactive</p>
    <p>3. 提取可复用的逻辑到composable函数</p>
  `,
});

// 评论排序方式
const sortType = ref<'latest' | 'hot'>('latest');

// 评论数据
const comments = ref<Comment[]>([
  {
    id: 1,
    user: '开发者A',
    avatar: '/static/images/avatar/2.jpg',
    time: '2小时前',
    content: '这篇文章写得太棒了，解决了我很多疑惑！',
    likes: 12,
    isLiked: false,
    createdAt: Date.now() - 2 * 60 * 60 * 1000,
    replies: [
      {
        id: 11,
        user: '前端小王子',
        avatar: '/static/images/avatar/1.jpg',
        time: '1小时前',
        content: '谢谢支持！后续会出更多实战教程',
      },
    ],
  },
  {
    id: 2,
    user: '技术爱好者',
    avatar: '/static/images/avatar/3.jpg',
    time: '5小时前',
    content: '请问ref和reactive在什么场景下选择使用比较好？',
    likes: 5,
    isLiked: true,
    createdAt: Date.now() - 5 * 60 * 60 * 1000,
    replies: [],
  },
]);

// 当前回复的评论
const currentReply = ref<{
  commentId: number | null
  replyTo: string | null
}>({
  commentId: null,
  replyTo: null,
});

// 新评论/回复内容
const newComment = ref('');

// 排序后的评论
const sortedComments = computed(() => {
  return [...comments.value].sort((a, b) => {
    if (sortType.value === 'latest') {
      return b.createdAt - a.createdAt;
    } else {
      return (b.likes * 2 + b.replies.length) - (a.likes * 2 + a.replies.length);
    }
  });
});

// 收藏文章
function toggleFavorite() {
  article.value.isFavorited = !article.value.isFavorited;
  uni.showToast({
    title: article.value.isFavorited ? '收藏成功' : '取消收藏',
    icon: 'none',
  });
}

// 点赞文章
function likeArticle() {
  article.value.likes += article.value.isLiked ? -1 : 1;
  article.value.isLiked = !article.value.isLiked;
}

// 点赞评论
function likeComment(comment: Comment) {
  comment.likes += comment.isLiked ? -1 : 1;
  comment.isLiked = !comment.isLiked;
}

// 设置当前回复
function setCurrentReply(commentId: number, replyTo: string) {
  currentReply.value = { commentId, replyTo };
  //   newComment.value = `回复 @${replyTo}: `;
  uni.pageScrollTo({
    selector: '#comment-input',
    duration: 300,
  });
}

// 提交评论/回复
function submitComment() {
  if (!newComment.value.trim())
    return;

  if (currentReply.value.commentId) {
    // 提交回复
    const comment = comments.value.find(c => c.id === currentReply.value.commentId);
    if (comment) {
      comment.replies.push({
        id: Date.now(),
        user: '当前用户',
        avatar: '/static/images/avatar/4.jpg',
        time: '刚刚',
        content: newComment.value,
        replyTo: currentReply.value.replyTo || undefined,
      });
      article.value.comments++;
    }
  } else {
    // 提交新评论
    comments.value.unshift({
      id: Date.now(),
      user: '当前用户',
      avatar: '/static/images/avatar/4.jpg',
      time: '刚刚',
      content: newComment.value,
      likes: 0,
      isLiked: false,
      createdAt: Date.now(),
      replies: [],
    });
    article.value.comments++;
  }

  newComment.value = '';
  currentReply.value = { commentId: null, replyTo: null };
  uni.showToast({ title: '发表成功', icon: 'success' });
}
</script>

<template>
  <view class="min-h-screen bg-gray-50 pb-24">
    <!-- 文章头部 -->
    <view class="bg-white px-6 pt-6 pb-4 shadow-sm sticky top-0 z-10">
      <view class="flex justify-between items-center mb-4">
        <uni-icons
          type="arrowleft"
          size="24"
          color="#333"
          @click="$emit('back')"
        />
        <uni-icons type="share" size="24" color="#9ca3af" />
      </view>

      <text class="text-xl font-bold text-gray-900 leading-tight">
        {{ article.title }}
      </text>

      <view class="flex items-center justify-between mt-4">
        <view class="flex items-center">
          <image
            :src="article.avatar"
            class="w-10 h-10 rounded-full border border-gray-200"
          />
          <view class="ml-3">
            <text class="text-sm font-medium text-gray-900 block">
              {{ article.author }}
            </text>
            <text class="text-xs text-gray-500">
              {{ article.date }} · {{ article.views }}阅读
            </text>
          </view>
        </view>

        <button
          class="flex items-center px-3 py-1 bg-gray-100 rounded-full text-sm"
          @click="toggleFavorite"
        >
          <uni-icons
            :type="article.isFavorited ? 'star-filled' : 'star'"
            size="16"
            :color="article.isFavorited ? '#f59e0b' : '#6b7280'"
          />
          <text class="ml-1">
            {{ article.isFavorited ? '已收藏' : '收藏' }}
          </text>
        </button>
      </view>
    </view>

    <!-- 文章内容 -->
    <view class="px-6 py-6 bg-white shadow-sm mb-3">
      <view class="flex flex-wrap mb-6">
        <view
          v-for="tag in article.tags"
          :key="tag"
          class="bg-blue-50 text-blue-600 text-xs px-3 py-1 rounded-full mr-2 mb-2"
        >
          {{ tag }}
        </view>
      </view>

      <rich-text
        :nodes="article.content"
        class="article-content text-gray-800 leading-relaxed"
      />

      <view class="flex justify-center mt-10 mb-4">
        <view class="w-24 h-px bg-gray-200" />
      </view>

      <view class="flex justify-between items-center">
        <view class="flex items-center space-x-6">
          <view
            class="flex items-center text-gray-500"
            @click="likeArticle"
          >
            <uni-icons
              :type="article.isLiked ? 'hand-up-filled' : 'hand-up'"
              size="18"
              :color="article.isLiked ? '#3b82f6' : '#9ca3af'"
            />
            <text class="ml-1 text-sm">
              {{ article.likes }}
            </text>
          </view>
          <view class="flex items-center text-gray-500">
            <uni-icons type="chat" size="18" color="#9ca3af" />
            <text class="ml-1 text-sm">
              {{ article.comments }}
            </text>
          </view>
        </view>
        <view class="text-gray-500 text-sm">
          阅读完毕
        </view>
      </view>
    </view>

    <!-- 评论区域 -->
    <view class="px-6 py-4 bg-white shadow-sm">
      <view class="flex justify-between items-center mb-6">
        <text class="text-lg font-bold text-gray-900">
          评论 {{ comments.length }}
        </text>
        <view class="flex space-x-3">
          <button
            class="px-3 py-1 rounded-full text-sm"
            :class="sortType === 'latest' ? 'bg-blue-50 text-blue-600' : 'bg-gray-100 text-gray-600'"
            @click="sortType = 'latest'"
          >
            最新
          </button>
          <button
            class="px-3 py-1 rounded-full text-sm"
            :class="sortType === 'hot' ? 'bg-blue-50 text-blue-600' : 'bg-gray-100 text-gray-600'"
            @click="sortType = 'hot'"
          >
            最热
          </button>
        </view>
      </view>

      <!-- 评论列表 -->
      <view class="space-y-5">
        <view
          v-for="comment in sortedComments"
          :key="comment.id"
          class="comment-item"
        >
          <view class="flex">
            <image
              :src="comment.avatar"
              class="w-10 h-10 rounded-full border border-gray-200 flex-shrink-0"
            />
            <view class="ml-3 flex-1">
              <view class="flex justify-between items-start">
                <text class="text-sm font-medium text-gray-900">
                  {{ comment.user }}
                </text>
                <text class="text-xs text-gray-400">
                  {{ comment.time }}
                </text>
              </view>
              <text class="text-sm text-gray-800 mt-1 block">
                {{ comment.content }}
              </text>

              <view class="flex items-center mt-2">
                <view
                  class="flex items-center text-gray-500 mr-4"
                  @click="likeComment(comment)"
                >
                  <uni-icons
                    :type="comment.isLiked ? 'hand-up-filled' : 'hand-up'"
                    size="14"
                    :color="comment.isLiked ? '#3b82f6' : '#9ca3af'"
                  />
                  <text class="ml-1 text-xs">
                    {{ comment.likes || '' }}
                  </text>
                </view>
                <text
                  class="text-xs text-gray-500"
                  @click="setCurrentReply(comment.id, comment.user)"
                >
                  回复
                </text>
              </view>
            </view>
          </view>

          <!-- 回复列表 -->
          <view
            v-if="comment.replies.length"
            class="mt-3 pl-3 border-l-2 border-gray-100 space-y-3"
          >
            <view
              v-for="reply in comment.replies"
              :key="reply.id"
              class="flex"
            >
              <image
                :src="reply.avatar"
                class="w-8 h-8 rounded-full border border-gray-200 flex-shrink-0"
              />
              <view class="ml-2 flex-1">
                <view class="flex justify-between items-start">
                  <text class="text-sm font-medium text-gray-900">
                    {{ reply.user }}
                    <text
                      v-if="reply.replyTo"
                      class="text-gray-500 font-normal"
                    >
                      回复 @{{ reply.replyTo }}
                    </text>
                  </text>
                  <text class="text-xs text-gray-400">
                    {{ reply.time }}
                  </text>
                </view>
                <text class="text-sm text-gray-800 mt-1 block">
                  {{ reply.content }}
                </text>

                <view class="mt-1">
                  <text
                    class="text-xs text-gray-500"
                    @click="setCurrentReply(comment.id, reply.user)"
                  >
                    回复
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 评论输入框 -->
    <view
      id="comment-input"
      class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-100 px-4 py-3"
    >
      <view class="flex flex-col">
        <view
          v-if="currentReply.commentId"
          class="flex items-center justify-between mb-1 px-2 py-1 bg-blue-50 rounded"
        >
          <text class="text-xs text-blue-600">
            回复 @{{ currentReply.replyTo }}
          </text>
          <uni-icons
            type="close"
            size="14"
            color="#3b82f6"
            @click="currentReply = { commentId: null, replyTo: null }; newComment = ''"
          />
        </view>

        <view class="flex items-end">
          <textarea
            v-model="newComment"
            class="flex-1 bg-gray-100 rounded-lg px-4 py-3 text-sm focus:outline-none"
            placeholder="写下你的评论..."
            placeholder-style="color: #9ca3af;"
            :adjust-position="false"
            :show-confirm-bar="false"
            auto-height
            :cursor-spacing="20"
            maxlength="500"
            style="min-height: 25px;"
          />
          <button
            class="ml-2 bg-blue-500 text-white text-sm px-4 py-3 rounded-lg mb-1"
            :disabled="!newComment.trim()"
            :class="{ 'opacity-50': !newComment.trim() }"
            @click="submitComment"
          >
            发送
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.article-content {
  h2 {
    font-size: 1.2rem;
    font-weight: 600;
    margin: 1.5rem 0 1rem;
    color: #111827;
  }

  p {
    margin-bottom: 1rem;
    line-height: 1.7;
  }

  strong {
    font-weight: 600;
  }
}

.comment-item {
  padding-bottom: 0.75rem;
  border-bottom: 1px solid #f3f4f6;

  &:last-child {
    border-bottom: none;
    padding-bottom: 0;
  }
}
</style>
